<?php

namespace common\models\ofc;

use Yii;
use common\helpers\Url;

/**
 * This is the model class for table "{{%ofc_season}}".
 *
 * @property int $id
 * @property int $competition_id 赛事ID
 * @property string $name 赛季名称
 * @property int $year 年份
 * @property string|null $logo 赛季LOGO
 * @property int $current 是否当前赛季
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class OfcSeason extends \common\db\ActiveRecord {

    use \common\traits\Constants;

    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 10;
    const CURRENT_YES = 1;
    const CURRENT_NO = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%ofc_season}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['competition_id', 'year', 'current', 'status', 'created_at', 'updated_at'], 'integer'],
            [['name'], 'required'],
            [['name'], 'string', 'max' => 50],
            [['logo'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'competition_id' => '赛事ID',
            'name' => '赛季名称',
            'year' => '年份',
            'logo' => '赛季LOGO',
            'current' => '是否当前赛季',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getEvent() {
        return $this->hasOne(OfcCompetition::class, ['id' => 'competition_id']);
    }

    /**
     * {@inheritdoc}
     */
    public function getBrand() {
        return Url::attach($this->logo);
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'id',
            'event',
            'name',
            'year',
            'logo' => 'brand',
            'current',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function findAllByType($type = 1) {
        $query = static::find()->alias('t');
        $query->innerJoinWith('event event');
        $query->andWhere([
            't.status' => static::STATUS_ACTIVE,
            'event.type' => $type
        ]);
        $query->orderBy([
            't.year' => SORT_DESC
        ]);
        return $query->all();
    }

}
